package com.space.components.domain.core.diff;


import com.space.components.domain.core.annotation.EnableEntityDiff;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author <a href="mailto:414563035@qq.com">Bedroom</a>
 * @date 2021/6/1 5:00 下午
 */
public class EnableEntityDiffHelper {
    final static List<String> DEFAULT_EXCLUDES = Arrays.asList("log", "context");
    private List<String> excludes;

    final private Map<String, Boolean> excludesMap = new ConcurrentHashMap<>();

    public void process(EnableEntityDiff annotation) {
        this.excludes = new ArrayList<>(Arrays.asList(annotation.exclude()));
        if (annotation.enableDefaultExclude()) {
            this.excludes.addAll(DEFAULT_EXCLUDES);
        }
    }

    public boolean isExclude(String name) {
        if (excludes == null) {
            return false;
        }
        return excludesMap.computeIfAbsent(name, n -> {
            for (String exclude : excludes) {
                if (Objects.equals(exclude, name)){
                    return true;
                }

                int flag = 0;
                if (exclude.startsWith("%")) {
                    flag++;
                    exclude = exclude.replaceFirst("%", "");
                    if (name.endsWith(exclude)) {
                        return true;
                    }
                }
                if (exclude.endsWith("%")) {
                    flag++;
                    exclude = exclude.substring(0, exclude.length() - 1);
                    if (flag == 1 && name.startsWith(exclude)) {
                        return true;
                    }
                }
                if (flag == 2 && name.contains(exclude)) {
                    return true;
                }
            }
            return false;
        });
    }
}
